//
//  ModifyPhoneVC.swift
//  Hyphenate-Demo-Swift
//
//  Created by cydida on 2018/12/8.
//  Copyright © 2018年 curtainups. All rights reserved.
//

import UIKit
import Hyphenate

class ModifyPhoneVC: UIViewController,UITextFieldDelegate {

    @IBOutlet weak var phoneField: UITextField!
    @IBOutlet weak var getCodeBtn: UIButton!
    @IBOutlet weak var codeField: UITextField!
    @IBOutlet weak var countryField: UITextField!
    
    var countdownTimer: Timer?
    
    var username = ""
    var phone = ""
    var phoneCode = ""
    
    
    var isCounting = false {
        willSet {
            if newValue {
                countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
                remainingSeconds = 60
                getCodeBtn.backgroundColor = UIColor.gray
                print("\(remainingSeconds)")
            } else {
                countdownTimer?.invalidate()
                countdownTimer = nil
                getCodeBtn.backgroundColor = UIColor.init(red: 0/255.0, green: 110/255.0, blue: 216/255.0, alpha: 1.0)
            }
            getCodeBtn.isEnabled = !newValue
        }
    }
    var remainingSeconds: Int = 0 {
        willSet {
            getCodeBtn.setTitle(EnStatic.getWord(keyWord: "code sent"), for: .normal)
            if newValue <= 0 {
                getCodeBtn.setTitle(EnStatic.getWord(keyWord: "get new code"), for: .normal)
                isCounting = false
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        getProfile()

        // Do any additional setup after loading the view.
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        countdownTimer?.invalidate()
        countdownTimer = nil
    }
    

    @IBAction func getCodeAction(_ sender: Any) {
        getCode()
    }
    
    @IBAction func saveAction(_ sender: Any) {
        
        if(phoneField.text == ""){
            self.show("please input your phone number")
            return;
        }
        if(codeField.text == ""){
            self.show("please input your code")
            return;
        }
        
        postCode()
    }
    
    @objc func sendButtonPhoneClick(sender: UIButton) {
        print("ask for phone code")
        // 启动倒计时
        isCounting = true
    }
    
    @objc func updateTime(timer: Timer) {
        // 计时开始时，逐秒减少remainingSeconds的值
        remainingSeconds -= 1
    }
    
    //MARK: 限制只能输入数字
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let aSet = NSCharacterSet(charactersIn:"0123456789+").inverted
        let compSepByCharInSet = string.components(separatedBy: aSet)
        let numberFiltered = compSepByCharInSet.joined(separator: "")
        return string == numberFiltered
    }

    
    //获取验证码
    func getCode() {
        
        let cuHTTP = CUHTTP.instance()
        
        let urlString = "code"
        
        var parameters: [String: Any]
        
        parameters = [
            "username" : username,
            "phone" :  phoneField.text!,
            "countryCode" : countryField.text!.replacingOccurrences(of: "+", with: "", options: .literal, range: nil),
            "registerType" : "updatePhone",
        ]
        
        print(parameters)
        
        weak var weakSelf = self
        
        cuHTTP.makePostData(url: urlString, parameters: parameters,
                            success: {response in
                                print(response?.response?.statusCode ?? "??")      //成功时，返回200
                                print("测试:\(String(describing: response?.response))")
                                weakSelf?.isCounting = true
        } ,
                            failure: {response in
                               weakSelf?.show( EnStatic.getWord(keyWord: "get code failed"))
        }
        )
        
        
        
    }
    
    //提交验证码和新手机号信息
    func postCode() {
        
        phoneCode = codeField.text!
        let cuHTTP = CUHTTP.instance()
        
        let urlString = "register"
        
        var parameters: [String: Any]
        
        parameters = [
            "username" : username,
            "phone" : phoneField.text!,
            "countryCode" : countryField.text!.replacingOccurrences(of: "+", with: "", options: .literal, range: nil),
            "code" : phoneCode,
            "registerType" : "updatePhone",
        ]
        
        print(parameters)
        
        weak var weakSelf = self
        
        cuHTTP.makePostData(url: urlString, parameters: parameters,
                            success: {response in
                                print(response?.response?.statusCode ?? "??")
                                if let resCode = response?.response?.statusCode {
                                    
                                    if(resCode == 200){
                                        weakSelf?.navigationController?.popViewController(animated: true)
                                    }
                                }
                                
        } ,
                            failure: {response in
                                weakSelf?.show(EnStatic.getWord(keyWord: "save failed"))
        }
        )
        
    }
    
    //获取旧的Profile信息
    func getProfile() {
        
        var urlString : String = ""
        
        urlString = "profile?username=" + EMClient.shared().currentUsername
        
        weak var weakSelf = self
        
        let cuHTTP = CUHTTP.instance()
        
        cuHTTP.makeGetData(url: urlString, success: {response in
            print("Response String: \(String(describing: response?.result.value))")
            print(response?.response?.statusCode ?? "??")      //成功时，返回200
            if let value = response?.result.value {
                let data = value.data(using: String.Encoding.utf8)! as NSData
                let json = try? JSONSerialization.jsonObject(with: data as Data,
                                                             options:.allowFragments) as! [String: Any]
                print(json ?? "??")
                let allEvents = json!["user"] as Any
                print(allEvents)
                
                let loopE = allEvents as! [String: Any]
                if let tmpStr0 = loopE["username"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        self.username = tmpStr1
                        //                        self.countryCode.text = self.username
                    }
                }
                //                if let tmpStr0 = loopE["phone"] {
                //                    if let tmpStr1 = (tmpStr0 as? String) {
                //                        self.phone = tmpStr1
                //                        self.phoneView.text = self.phone
                //                    }
                //                }
                
            }
        },
                           failure:{ response in
                            print(response ?? " ")
                            weakSelf?.show(EnStatic.getWord(keyWord: "get data failed"))
        }
        )
        
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
